﻿#region Copyright

// All Material Copyright © 2008-2010 Dynamic Concepts Development Corp., All Rights Reserved
// 
// For further information please contact SoftwareSupport@dynconcepts.com
// 
// Dynamic Concepts Development Corp.  311 W 57th St. Suite #422, New York, NY 10019

#endregion

#region Using References

using System;

#endregion

namespace DynConDev.CorpLib.CommandLineParser
{
    public abstract class CommandProcessor
    {
        private readonly CommandLine r_CommandLine;
        private readonly CommandOptionHandlerDictionary r_CommandOptionHandlers;


        protected CommandProcessor(CommandLine commandLine, CommandOptionHandlerDictionary commandOptionHandlers)
        {
            if (commandLine == null)
                throw new ArgumentNullException("commandLine");
            if (commandOptionHandlers == null)
                throw new ArgumentNullException("commandOptionHandlers");
            r_CommandLine = commandLine;
            r_CommandOptionHandlers = commandOptionHandlers;
        }

        protected CommandLine CommandLine
        {
            get { return r_CommandLine; }
        }

        protected OptionCollection ExecutableOptions
        {
            get { return r_CommandLine.ExecutableOptions; }
        }

        protected OptionCollection CommandOptions
        {
            get { return r_CommandLine.Command.CommandOptions; }
        }

        protected ParameterCollection Parameters
        {
            get { return r_CommandLine.Parameters; }
        }

        protected abstract void ShowCommandUsage();


        protected virtual bool ValidateExecutableOptions(OptionCollection executableOptions)
        {
            return true;
        }

        protected virtual bool ValidateCommandOptions(OptionCollection commandOptions)
        {
            return r_CommandOptionHandlers.Execute(this, commandOptions);
        }

        protected virtual bool ValidateParameters(ParameterCollection parameters)
        {
            return true;
        }

        protected void ValidateCommandLine()
        {
            bool success = true; // optimist;
            if (r_CommandLine == null)
                throw new Exception();
            if (!ValidateExecutableOptions(ExecutableOptions))
            {
                ShowCommandUsage();
                success = false;
            }
            if (!ValidateCommandOptions(CommandOptions))
            {
                ShowCommandUsage();
                success = false;
            }
            if (!ValidateParameters(Parameters))
            {
                ShowCommandUsage();
                success = false;
            }
            if (!success)
            {
                ShowCommandUsage();
                throw new Exception();
            }
        }
    }
}